import React, {Component} from 'react';
import { Form, Input, Button, Icon, Upload, Modal, message } from 'antd';
import './index.less';
import axios from 'axios';
import {connect} from 'react-redux';
const FormItem = Form.Item;
import Bread from '../common/Bread/index';
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'

class info extends Component {
  constructor(props) {
    super(props);
    this.state = {
      name: '',
      cardId: '',
      email: '',
      uploadFront: '',
      uploadBack: '',
      uploadHand: '',
      cardFront: [],
      cardBack: [],
      cardHand: []
    }
  }
  componentWillMount(){
    this.getInfo();
  }
  normFile = (e) => {
    if (Array.isArray(e)) {
      return e;
    }
    return e && e.fileList;
  }
  getInfo = () => {
    const Token = localStorage.getItem("token");
    const $this = this;
    axios({
      method: 'get',
      url: '/api/customer/userid/tx',
      headers: {
        'Content-Type': 'application/json',
        Authorization:Token,
      }
    })
    .then(function(response){
      if(response.data.code == '200'){
        let dataFrontCard = []
        let dataBackCard = []
        let dataImageCard = []
        if(response.data.data.frontCard){
          dataFrontCard = [{
            uid: -1,
            name: '',
            status: 'done',
            url: response.data.data.frontCard,
            thumbUrl: response.data.data.frontCard
          }]
        }
        if(response.data.data.backCard){
          dataBackCard = [{
            uid: -1,
            name: '',
            status: 'done',
            url: response.data.data.backCard,
            thumbUrl: response.data.data.backCard
          }]
        }
        if(response.data.data.imageCard){
          dataImageCard = [{
            uid: -1,
            name: '',
            status: 'done',
            url: response.data.data.imageCard,
            thumbUrl: response.data.data.imageCard
          }]
        }
        $this.setState({
          name: response.data.data.username ? response.data.data.username :'',
          cardId: response.data.data.idNo,
          email: response.data.data.email,
          cardFront: dataImageCard,
          cardBack: dataBackCard,
          cardHand: dataImageCard
        })
      } else if (response.data.code == '201') {
        message.error('个人信息不完善，请先完善个人信息。');
      }
    })
    .catch(function(error){
      message.error('请求失败，请稍后再试。')
    })
  }
  changeInfo = (e) => {
    e.preventDefault();
    const $this = this;
    const Token = localStorage.getItem("token");
    $this.props.form.validateFields((err, values) => {
      if (!err) {
        axios({
          method: 'POST',
          url: '/api/customer/userid/save',
          headers: {
            'Content-Type': 'application/json',
            Authorization:Token,
          },
          data: {
            username: values.name,
            idNo: values.cardId,
            email: values.email,
            frontCard: Array.isArray(values.uploadFront) ? values.uploadFront[0].url : values.uploadFront.file.response.data.url,
            backCard: Array.isArray(values.uploadBack) ? values.uploadBack[0].url : values.uploadBack.file.response.data.url,
            imageCard: Array.isArray(values.uploadHand) ? values.uploadHand[0].url : values.uploadHand.file.response.data.url
          }
        })
        .then(function(response){
          if(response.data.code == '200'){
            message.success("个人信息更新成功");
            $this.props.form.resetFields();
            $this.getInfo();
          } else if (response.data.code == '201') {
            message.error('个人信息不完善，请先完善个人信息。');
          } else if (response.data.code == '202') {
            message.error('身份证号码无效！');
          } else if (response.data.code == '203') {
            message.error('邮箱无效！');
          } else if (response.data.code == '204') {
            message.error('身份证正面照片无效！');
          } else if (response.data.code == '205') {
            message.error('身份证反面照片无效！');
          } else if (response.data.code == '206') {
            message.error('手持身份证照片无效！');
          }
        })
        .catch(function(error){
          message.error('请求失败，请稍后再试。')
        })
      }
    })
    
  }
  uploadImg = (name, fileArr) => {
    const Token = localStorage.getItem("token");
    const $this = this;
    const upload = {
      action: '/api/customer/org/upload',
      accept: 'image/*',
      listType: 'picture',
      headers: {
        Authorization: Token
      },
      className: 'upload-list-inline',
      beforeUpload (file) {
        const imgLimit = file.size / 1024 / 1024 < 10;
        if (!imgLimit) {
          message.error('图片大小不能超过10M!');
          return false
        }
        return imgLimit;
      },
      onChange(info) {
        // 对于受控模式，你应该在 onChange 中始终 setState fileList，保证所有状态同步到 Upload 内,否则一直uploading
        $this.setState({
          [fileArr]: [info.file]
        })
        if (info.file.status === 'done' && info.file.response.code === '200') {
          $this.setState({
            [name]: [info.file.response.data.url],
            [fileArr]: [info.file]
          })
          message.success('上传成功！');
        } else if (info.file.status === 'error') {
          message.error('上传失败！');
        }
      },
      onRemove(info) {
        $this.props.form.setFieldsValue({
          [name]: ''
        })
        $this.setState({
          [fileArr]: [],
          [name]: '',
        })
      },
    };
    return upload;
  }
  render() {
    const { getFieldDecorator } = this.props.form;
    const $this = this;
    return (
      <div className="changeBox">
        <Bread bread={['账户服务',['信息管理','info']]}/>         
        <Form onSubmit={this.changeInfo}> 
          <div>
            <h3 className="changeTitle">信息管理</h3>                  
            <FormItem
              label="真实姓名"
              labelCol={{ span: 5 }}
              wrapperCol={{ span: 11 }}
            >
              {getFieldDecorator('name', { 
                rules: [{ required: true, message: '请输入真实姓名'  }],
                initialValue: this.state.name
              })(
                <Input type="text" placeholder='请输入真实姓名' className="signInput" />
              )}
            </FormItem>
            <FormItem
              label="身份证号"
              labelCol={{ span: 5 }}
              wrapperCol={{ span: 11 }}
            > 
              {getFieldDecorator('cardId',{
                rules: [{required: true, message: '请输入有效身份证号', pattern: /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/ }],
                initialValue: this.state.cardId
              })(
                <Input type="text" placeholder='请输入身份证号' maxLength={18} />
              )}
            </FormItem>
            <FormItem
              label="邮箱"
              labelCol={{ span: 5 }}
              wrapperCol={{ span: 11 }}
            > 
              {getFieldDecorator('email',{
                rules: [{required: true, message: '请输入邮箱' }],
                initialValue: this.state.email
              })(
                <Input type="text" placeholder='请输入邮箱' />
              )}
            </FormItem>
            <FormItem
              label="身份证正面"
              labelCol={{ span: 5 }}
              wrapperCol={{ span: 11 }}
            >
              {getFieldDecorator('uploadFront', {
                rules: [{ required: true, message: '请上传身份证正面!', }],
                initialValue: $this.state.cardFront
              })(
                <Upload {...$this.uploadImg('uploadFront', 'cardFront')} fileList={$this.state.cardFront}>
                  <Button type="primary" className="uploadBtn">上传图片</Button>
                </Upload>
              )}
            </FormItem>
            <FormItem
              label="身份证反面"
              labelCol={{ span: 5 }}
              wrapperCol={{ span: 11 }}
            >
              {getFieldDecorator('uploadBack', {
                rules: [{ required: true, message: '请上传身份证反面照片!', }],
                initialValue: $this.state.cardBack
              })(
                <Upload {...$this.uploadImg('uploadBack', 'cardBack')} fileList={$this.state.cardBack}>
                  <Button type="primary" className="uploadBtn">上传图片</Button>
                </Upload>
              )}
            </FormItem>
            <FormItem
              label="手持身份证"
              labelCol={{ span: 5 }}
              wrapperCol={{ span: 11 }}
            >
              {getFieldDecorator('uploadHand', {
                rules: [{ required: true, message: '请上传手持身份证照片!', }],
                initialValue: $this.state.cardHand
              })(
                <Upload {...$this.uploadImg('uploadHand', 'cardHand')} fileList={$this.state.cardHand}>
                  <Button type="primary" className="uploadBtn">上传图片</Button>
                </Upload>
              )}
            </FormItem>
            
            <div className="confirmChange">
              <Button type="primary" htmlType="submit" className="">确认修改</Button>
            </div>
          </div>
        </Form>
      </div>  
    )
  }
}
  
const Info = Form.create()(info);
export default connect((state) => {
  return { ...state };
})(Info);
